package com.d3works.apps.quality.db.repo;

import com.d3works.apps.base.db.repo.SequenceRepository;
import com.d3works.apps.base.service.administration.SequenceService;
import com.d3works.apps.quality.db.QualityControl;
import com.d3works.exception.D3worksException;
import com.d3works.exception.service.TraceBackService;
import com.google.common.base.Strings;
import com.google.inject.Inject;

public class QualityControlManagementRepository extends QualityControlRepository {

  @Inject private SequenceService sequenceService;

  /**
   * Generate and set sequence in reference with predefined prefix.
   *
   * @param qualityControl Overridden quality control object to set reference on onSave event.
   */
  @Override
  public QualityControl save(QualityControl qualityControl) {

    if (Strings.isNullOrEmpty(qualityControl.getReference())) {
      try {
        qualityControl.setReference(
            sequenceService.getSequenceNumber(
                SequenceRepository.QUALITY_CONTROL, null, QualityControl.class, "reference"));
      } catch (D3worksException e) {
        TraceBackService.traceExceptionFromSaveMethod(e);
      }
    }
    return super.save(qualityControl);
  }
}
